package com.ias.system.service.impl.oss;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.ias.system.model.vo.FileInfoVO;
import com.ias.system.service.OssService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;

/**
 * 本地文件存储服务（开发环境使用）
 *
 * @author magy
 * @since 3.0.0
 */
@Slf4j
@Service
@ConditionalOnProperty(value = "oss.type", havingValue = "local", matchIfMissing = true)
public class LocalOssService implements OssService {

    private static final String UPLOAD_DIR = "uploads";

    @Override
    @SneakyThrows
    public FileInfoVO uploadFile(MultipartFile file) {
        // 生成文件名(日期文件夹)
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        String uuid = IdUtil.simpleUUID();
        String datePath = DateUtil.format(LocalDateTime.now(), "yyyyMMdd");
        String fileName = datePath + "/" + uuid + "." + suffix;
        
        // 创建上传目录
        String uploadPath = UPLOAD_DIR + "/" + fileName;
        File destFile = new File(uploadPath);
        FileUtil.mkParentDirs(destFile);
        
        // 保存文件
        file.transferTo(destFile);
        
        log.info("文件上传成功: {}", uploadPath);
        
        // 返回文件信息
        FileInfoVO fileInfo = new FileInfoVO();
        fileInfo.setName(fileName);
        fileInfo.setUrl("/files/" + fileName);
        return fileInfo;
    }

    @Override
    public boolean deleteFile(String filePath) {
        try {
            // 从URL中提取文件路径
            String fileName = filePath.replace("/files/", "");
            File file = new File(UPLOAD_DIR + "/" + fileName);
            if (file.exists()) {
                FileUtil.del(file);
                log.info("文件删除成功: {}", filePath);
                return true;
            }
            log.warn("文件不存在: {}", filePath);
            return false;
        } catch (Exception e) {
            log.error("文件删除失败: {}", filePath, e);
            return false;
        }
    }
}


